// pages/shezhi/shebei.js
import QRCode from '../../../js/weapp-qrcode.js'

var utilBT = require('../../../js/utilBT.js');
var utilData = require('../../../js/utilData.js');


const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scrollHeight: 0,
        findtext: '搜索设备',
        setInter: '',
        equs: [],
        equconn0: false,
        equ: {},
        setmac: {},
        hascode: false,
        sn: 100,
        modalHidden1: true

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this
        app.log('== onLoad')
        that.endSetInter()
        that.startSetInter()
        that.datastrt()

        if (!app.globalData.equconn0) {
            that.findequs()
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

        this.calculateScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        app.log('== onShow')
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.endSetInter()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    datastrt: function () {
        app.log('==>>定时处理数据')
        var that = this
        that.setData({
            equs: app.globalData.equs,
            equconn0: app.globalData.equconn0,
            equ: app.globalData.equ,
            setmac: app.globalData.setmac,
            sn: app.globalData.BLE_SN
        })
        if (that.data.equs.length > 0) {
            that.setData({
                findtext: '重新扫描'
            })
        }


        if (that.data.equconn0) {
            that.onGetData()
            that.setData({
                hascode: true
            })
            if (app.globalData.BLE_SN == 100) {
                utilBT.getSn(16)
                wx.showLoading({
                    title: '设备识别中',
                    mask: true,
                })
                setTimeout(function () {
                    wx.hideLoading()
                }, 2000)
            }

        }
        // that.equCode()

    },

    startSetInter: function () {
        var that = this;
        // that.datastrt()
        //将计时器赋值给setInter
        that.data.setInter = setInterval(
            function () {
                that.datastrt()
            }
            , 2000);
    },
    endSetInter: function () {
        var that = this;
        //清除计时器  即清除setInter
        clearInterval(that.data.setInter)
    },

    startbind: function (e) {
        app.log('====>>点击连接,绑定设备')
        app.globalData.BLE_SN = 100
        app.globalData.SEND_NUM = 0

        app.log(e.currentTarget.dataset.equ)

        utilBT.bindBT(e.currentTarget.dataset.equ.localName, e.currentTarget.dataset.equ.deviceId, e.currentTarget.dataset.equ.mac)

        utilBT.connToDid()

    },
    stopbind: function () {
        utilBT.closeconn(app.globalData.equ.deviceId)
        utilBT.unbindBT()

        wx.navigateBack({
            delta: 1
        })

    },
    equCode: function () {

        var that = this
        app.log('====生成二维码')
        app.log(that.data.equconn0 && !that.data.hascode)
        if (that.data.equconn0 && !that.data.hascode) {
            that.setData({
                hascode: true
            })
            let equtext = that.data.equ.name + ',' + that.data.equ.mac
            new QRCode('myQrcode', {
                text: equtext,

                padding: 12, // 生成二维码四周自动留边宽度，不传入默认为0
                correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
                callback: (res) => {
                    app.log(res.path)
                    // 接下来就可以直接调用微信小程序的api保存到本地或者将这张二维码直接画在海报上面去，看各自需求

                }
            })
        }

    },
    findequs: function () {
        app.log('==>>重新扫描')
        var that = this
        app.globalData.equs = []
        that.setData({
            equs: []
        })
        utilBT.closeconn(app.globalData.equ.deviceId)
        utilBT.unbindBT()

        app.log('==>>app.globalData.equ')
        app.log(app.globalData.equ)

        utilBT.checkbluetooandlocation(function (res) {
            if (res) {
                wx.showToast({
                    title: '搜索中',
                    icon: 'loading',
                    mask: true,
                    duration: 5000,
                })
                utilBT.initBluetooth()
                utilBT.searchBluetooth()
            }
        })

    },
    scancode: function () {
        var that = this

        utilBT.closeconn(app.globalData.equ.deviceId)
        utilBT.unbindBT()


        utilBT.checkbluetooandlocation(function (res) {
            if (res) {
                // 允许从相机和相册扫码
                wx.scanCode({
                    onlyFromCamera: false,
                    success(res) {
                        let equ = res.result.split(",")

                        wx.showModal({
                            title: '是否绑定设备 ' + equ[0] + ' ？',
                            mask: true,
                            icon: 'none',
                            duration: 3000,
                            success: function (res) {
                                if (res.confirm) {
                                    app.log('============>>确认绑定')
                                    utilBT.bindBT(equ[0], null, equ[1])

                                    utilBT.initBluetooth()
                                    utilBT.searchBluetooth()

                                    // 		//建立连接
                                    utilBT.connToDid()

                                } else if (res.cancel) {
                                    app.log('============>>取消绑定')
                                }
                            },

                        })
                    }
                })

            }
        })
    },

    /**
     * 计算scrollview高度
     */
    calculateScrollViewHeight: function () {
        let that = this;
        let query = wx.createSelectorQuery().in(this)
        //根据节点id查询节点部分的高度（px单位）
        query.select('#buttons').boundingClientRect();

        query.exec((res) => {
            // 分别取出节点的高度
            let buttonsHeight = res[0].height;
            // 然后窗口高度（wx.getSystemInfoSync().windowHeight）减去其他不滑动界面的高度
            let scrollViewHeight = wx.getSystemInfoSync().windowHeight - buttonsHeight - 50;
            app.log(scrollViewHeight)
            // 算出来之后存到data对象里面
            that.setData({
                scrollHeight: scrollViewHeight
            });
        })
    },

    onGetData: function () {
        var that = this

        wx.onBLECharacteristicValueChange(function (res) {
            app.log('====>>' + app.globalData.equ.name + '接收到的数据')
            utilData.deData(res, function (res) {

                app.log('==>>res_sn:' + res)
                if (res.code == 50 || res.code == 1) {
                    that.setData({
                        sn: app.globalData.BLE_SN,
                    })
                    if (that.data.setmac.mac != app.globalData.equ.mac) {
                        let _setmac = {}
                        _setmac.mac = app.globalData.equ.mac
                        _setmac.nickName = ''
                        app.globalData.setmac = _setmac
                    }
                }
            })

        })
        // if (that.data.sn > 700) {
        //     wx.hideLoading()
        // }

    },

    unGetData: function () {
        wx.offBLECharacteristicValueChange(function (res) {

            app.log('====>>取消监听蓝牙数据')
            app.log(res)
        })
    },
    toCeliang: function () {

        wx.switchTab({
            url: '/pages/celiang/celiang'
        })
    },
    toShuoMing: function (e) {
        let value = e.currentTarget.dataset.val
        wx.navigateTo({
            url: "/pages/index/shuoming/shuoming?val=" + value
        })
    },

    modalTap1: function (e) {
        app.log('==>>打开弹窗')
        this.setData({
            modalHidden1: false
        })
    },
    modal_can1: function () {
        app.log('==>>点击取消')
        this.setData({
            modalHidden1: true
        })
    },
    modal_con1: function (e) {
        let that = this
        app.log('==>>点击确定')
        that.setData({
            modalHidden1: true
        })
    },
    getIn: function (e) {
        let that = this
        app.log('==>>失去焦点')
        let equNickName = e.detail.value
        app.log(equNickName)

        if (equNickName == null || equNickName == '' || equNickName.toString().length == 0) {
            equNickName = 'BEL-EMP-Ui'
        }

        app.globalData.setmac.nickName = equNickName
        app.globalData.setmac.mac = that.data.equ.mac

        wx.setStorageSync('set_equ_nick_name', equNickName)
        wx.setStorageSync('set_equ_mac', that.data.equ.mac)


    },

})
